package com.itheima.luence;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.File;
import java.io.IOException;

public class LuenceQuery {
    public void search(Query query) throws IOException {
        //索引目录对象
        Directory directory = FSDirectory.open(new File("indexDir"));
        //索引读取工具
        IndexReader reader = DirectoryReader.open(directory);
        //索引搜索工具
        IndexSearcher searcher = new IndexSearcher(reader);


        TopDocs topDocs = searcher.search(query, 10);
        //获取总条数
        System.out.println("本次共搜索到：" + topDocs.totalHits + "条数据");

        //获得文档对象
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int docId = scoreDoc.doc;
            //根据编号找文档
            Document document = reader.document(docId);

            String title = document.get("title");
            System.out.println("title = " + title);

        }
    }
}
